import spacy
import json
from flask import Flask, jsonify, request, Response

# 加载 SpaCy 中文模型
nlp = spacy.load("zh_core_web_sm")

app = Flask(__name__)

def preprocess_text(text):
    # 使用 SpaCy 进行命名实体识别
    doc = nlp(text)
    
    # 识别实体
    entities = [{"Text": ent.text, "Label": ent.label_} for ent in doc.ents]
    
    # 按句子拆分文本
    sentences = [sent.text for sent in doc.sents]
    
    # 返回预处理后的数据
    result = {
        "Entities": list(entities),  # 确保将实体列表转换为标准列表
        "Sentences": sentences
    }
    
    return result

@app.route('/spacy', methods=['POST'])
def preprocess():
    data = request.get_json()
    text = data.get("text", "")

    # 进行预处理
    processed_result = preprocess_text(text)
    print(f"Entities: {processed_result.values()}")    

    # 返回预处理后的数据
    res = Response(json.dumps(processed_result, ensure_ascii=False), content_type="application/json; charset=utf-8")
    
    return res

@app.route('/parse_input', methods=['POST'])
def parse_text():
    # 从请求中获取用户输入
    content = request.json.get('content', '')

    if not content:
        return jsonify({"error": "Content is required"}), 400

    # 使用 spaCy 进行文本处理
    doc = nlp(content)
    
    # 提取实体和关键词
    entities = [{"text": ent.text, "label": ent.label_} for ent in doc.ents]
    tokens = [token.text for token in doc if not token.is_stop]  # 去除停用词

    # 构造响应
    response = {
        "entities": entities,
        "tokens": tokens,
        "text": content
    }

    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)